<template>
    <div>
            <div id="components-form-demo-advanced-search">
                <a-form class="ant-advanced-search-form" :form="form" @submit="getTaskByUser">
                    <a-row :gutter="34">
                        <a-col :span="3">
                            <a-button type="primary" @click="getSum">筛选项积分</a-button>
                        </a-col>
                        <a-col :span="5">
                            <a-button type="primary" @click="exportData">导出</a-button>
                        </a-col>
                    </a-row>
                    <a-row :gutter="24" style="margin-top: 15px">
                        <a-col :span="4">
                            <a-form-item>
                                <a-input
                                    v-decorator="[`name`]"
                                    placeholder="请输入任务信息"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-form-item>
                                <a-select v-decorator="['time']" placeholder="请选择时间">
                                    <a-select-option v-for="item in drd.times" :value="item.value" :key="item.name">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-form-item>
                                <a-select v-decorator="['inspectionId']" placeholder="请选择服务类型">
                                    <a-select-option :value="undefined">全部</a-select-option>
                                    <a-select-option v-for="item in drd.inspection" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-form-item>
                                <a-select v-decorator="['status']" placeholder="请选择订单状态">
                                    <a-select-option v-for="item in drd.status" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="4">
                            <a-form-item>
                                <a-button type="primary" html-type="submit">查询</a-button>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        <a-table :columns="columns" :dataSource="list" :pagination="pagination" rowKey="id" bordered id="update-table-1">
            <template slot="time" slot-scope="text, record">
                {{record.startTime }}~
                <br/>
                {{ record.endTime }}
            </template>
            <span slot="action">
                <a-button type="link">详情</a-button>
            </span>
        </a-table>
        <a-modal v-model="showSum" @ok="showSum = false" width="300px" :closable="false"
                 :cancelButtonProps="{ props: {type: 'primary'}}"
                 centered
                 :maskClosable = 'false'
                 :keyboard = 'false'>
            <div style="text-align: center">
                所筛选项目积分为{{sum}}分
            </div>
        </a-modal>
    </div>
</template>

<script>
import moment from 'moment'
import { export_xlsx } from '@/utils/xlsx.js'
export default {
    props: ['userId'],
    data(){
        return {
            form: this.$form.createForm(this, { name: 'search' }),
            list: [],
            columns: [
                {title: '订单编号', dataIndex: 'number', align: 'center'},
                {title: '任务名称', dataIndex: 'name', align: 'center'},
                {title: '任务起止时间', scopedSlots: {customRender: 'time'}, align: 'center'},
                {title: '所用积分', dataIndex: 'total', align: 'center'},
                {title: '订单状态', dataIndex: 'statusName', align: 'center'},
                {title: '操作', scopedSlots: {customRender: 'action'}, align: 'center'},
            ],
            pagination: {
                current: 1,
                total: 0,
                pageSize: 10,
                showQuickJumper: true,
                onChange: (page, size) => {
                    this.handleChange(page, size)
                },
            },
            drd: {
                times: [
                    { name: '全部', value: undefined },
                    { name: '最近一周', value: moment().subtract(7, 'days').calendar() },
                    { name: '最近一月', value: moment().subtract(1, 'month').calendar() },
                    { name: '最近三月', value: moment().subtract(3, 'month').calendar() },
                    { name: '最近半年', value: moment().subtract(6, 'month').calendar() },
                    { name: '最近一年', value: moment().subtract(12, 'month').calendar() },
                ],
                inspection: [],
                status: [
                    { id: undefined, name: '所有订单状态' },
                    { id: 0, name: '任务已驳回' },
                    { id: 1, name: '任务已发出' },
                    { id: 2, name: '调度已确认' },
                    { id: 3, name: '飞手已接收' },
                    { id: 4, name: '飞行结束' },
                    { id: 5, name: '任务已完成' },
                ],
            },
            sum: 0,
            showSum: false
        }
    },
    methods: {
        async getInspection(){
            let { data: {data} } = await this.http('get', '/inspection/selectLikeList', { pageNo: 1, pageSize: 100 })
            this.drd.inspection = data || []
        },
        async getTaskByUser(){
            let search = this.form.getFieldsValue(),
                { current, pageSize } = this.pagination
            if(search.time){
                var reg = new RegExp( '/' , "g" )
                search.time = search.time.replace( reg , '-' ) + '~' + moment().format('YYYY-MM-DD')
            }
            // console.log(search)
            // console.log('this.userId--->',this.$route.params.id)
            let { data: {data, totalCount}} = await this.http('get', '/task/list', {userId: this.$route.params.id, ...search, pageNo: current, pageSize})
            this.list = data || []
            this.pagination.total = totalCount
        },
        handleChange(page, size) {
            this.pagination.current = page;
            this.pagination.pageSize = size;
            this.getTaskByUser()
        },
        async getSum(){
            let search = this.form.getFieldsValue()
            if(search.time){
                var reg = new RegExp( '/' , "g" )
                search.time = search.time.replace( reg , '-' ) + '~' + moment().format('YYYY-MM-DD')
            }
            let { data } = await this.http('get', '/task/sumPoint', { userId: this.$route.params.id, ...search })
            this.sum = data.point
            this.showSum = true
        },
        async exportData(){
            let search = this.form.getFieldsValue(),
                { current } = this.pagination
            if(search.time){
                var reg = new RegExp( '/' , "g" )
                search.time = search.time.replace( reg , '-' ) + '~' + moment().format('YYYY-MM-DD')
            }
            // console.log(search)
            // console.log('this.userId--->',this.$route.params.id)
            let { data: {data}} = await this.http('get', '/task/list', {userId: this.$route.params.id, ...search, pageNo: current, pageSize: 1000}),
                list = data || [],
            header_map = {
                'number': '订单编号',
                'name': '任务名称',
                'time': '任务起止时间',
                'total': '所用积分',
                'statusName': '任务状态',
            }
            if(!list.length){
              return this.$message({
                type: 'error',
                message: '无数据，导出失败！'
              })
            }

            function get_val(obj, exp) {
                var val = obj;
                exp = exp.split('.');
                exp.forEach(function(k) {
                    val = val[k];
                });
                return val;
            }
            function filtrName(arr) {
                if(arr == '' || arr == null){
                    return '暂无'
                }
                let list = arr.map(v=>{
                    return v.name
                })
                return list.join()
            }
            let xlsx_list = (list && list.length) ? list.map(item => {
                let _item = {}
                for(let key in header_map){
                    let val = '暂无'
                    try {
                        val = get_val(item, key)
                    } catch (e) {}
                    _item[header_map[key]] = val || '暂无'
                }
                _item['任务起止时间'] = `${item.startTime || '暂无'} ~ ${item.endTime || '暂无'}`
                return _item
            }) : []
            let userinfo = JSON.parse(localStorage.getItem('user_info'))
            export_xlsx(xlsx_list, `${userinfo.name + moment().format('YYYY-MM-DD')}`)
        },
    },
    async created(){
        await Promise.all([
            this.getInspection(),
            this.getTaskByUser()
        ])
    },
}
</script>

<style>

</style>